//
//  SearchGroupViewController.m
//  SouthChina
//
//  Created by kc on 15/8/7.
//  Copyright (c) 2015年 科创. All rights reserved.
//通讯录中通用搜索页面

#import "SearchGroupViewController.h"
#import "ContactDao.h"
#import "GroupTableViewCell.h"
#import "MessageViewController.h"
#import "SearchinforTableViewCell.h"
#import "GroupInfoViewController.h"
#import "FriendDetailViewController.h"
#import "SDRefresh.h"
#import "TabbarViewController.h"
#import "TabbarView.h"

@interface SearchGroupViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray *searchArr; //搜索列表(本地)
    NSMutableArray *stragergrpArr; //搜索陌生群
    NSMutableArray *strageruserArr; //搜索陌生人
    
    BOOL bEditing;//已经编辑
    NSString *sSearchKey;
    SDRefreshFooterView *refreshOrganizationFooterView;   //机构列表刷新
    NSInteger  organizationPageNo;      //当前查询的组织机构群页数
    int pageSize;                       //每次翻页数量
    UITextField *searchField;
    
}
@property (strong, nonatomic) IBOutlet UISearchBar *searchbar;
@property (strong, nonatomic) IBOutlet UITableView *tablistview;
@property (strong, nonatomic) IBOutlet UITableView *tablestragegrp; //陌生群
@property (strong, nonatomic) IBOutlet UITableView *tablestrageuser;//陌生人
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *tablelistbottom;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *tbstrangegrpbtm;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *tbstrangeusrbtm;

@end

@implementation SearchGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    stragergrpArr = [[NSMutableArray alloc]init];
    strageruserArr = [[NSMutableArray alloc]init];
    organizationPageNo = 1;
    pageSize = 10;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
   [self addTitleBarWithBackBtn:@"通讯录搜索" needReturn:TRUE];
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"SearchGroupViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    
    _tablistview.delegate = self;
    _tablistview.dataSource = self;
    _tablistview.bounces = YES;
    _tablistview.tag = LOCAL_GROUP;
    
    _tablestragegrp.delegate = self;
    _tablestragegrp.dataSource = self;
    _tablestragegrp.bounces = YES;
    _tablestragegrp.tag = STRANGER_GROUP;
    
    _tablestrageuser.delegate = self;
    _tablestrageuser.dataSource = self;
    _tablestrageuser.bounces = YES;
    _tablestrageuser.tag = STRANGER_USER;
    
    
    //ios7.0 之后UISearchBar 结构发生了变化
    if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
        searchField=[_searchbar.subviews objectAtIndex:1];
    else
        searchField=[((UIView *)[_searchbar.subviews objectAtIndex:0]).subviews lastObject];
    [searchField setReturnKeyType:UIReturnKeyDone];
    
    _searchbar.delegate = self;
    _searchbar.placeholder = @"输入关键字或学工号搜索";
    _searchbar.showsCancelButton=NO;
    _searchbar.barStyle=UIBarStyleDefault;
    _searchbar.keyboardType = UIKeyboardTypeDefault;
    
    searchArr = [[NSMutableArray alloc] init];
    bEditing = FALSE;
    sSearchKey = @"";
    
    _tablistview.hidden = NO;
    _tablestragegrp.hidden = YES;
    _tablestrageuser.hidden = YES;
    [_tablistview reloadData];
    [self setupHeader];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification
                                                  object:nil];
}

# pragma mark Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    _tablelistbottom.constant = height;
    _tbstrangegrpbtm.constant = height;
    _tbstrangeusrbtm.constant = height;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    _tablelistbottom.constant = 0;
    _tbstrangegrpbtm.constant = 0;
    _tbstrangeusrbtm.constant = 0;
}

//完成按钮后的操作
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@".....%@",searchText);
    if(searchText.length>0)
    {
        NSLog(@"搜索长度为：%lu",(unsigned long)searchText.length);
        bEditing = TRUE;
        sSearchKey = searchText;
        //先在本地搜索，本地搜索不到的话，在服务器上搜索
        searchArr = [self searchGroupList:searchText];
    }
    else
    {
        bEditing = FALSE;
        sSearchKey = @"";
    }
    _tablistview.hidden = NO;
    _tablestragegrp.hidden = YES;
    _tablestrageuser.hidden = YES;
    [_tablistview reloadData];
}


// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"取消");
    kAppDelegate.needRefrsh=YES;
    [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
}

//根据关键字或者列表
-(NSMutableArray *)searchGroupList:(NSString *)searchkey
{
    NSMutableArray * orgArray = [[NSMutableArray alloc] init];
    if([searchkey isEqualToString:@""])
        return  orgArray;
    
   //需要对数据进行剔重20151010
    NSString *swheresql = [NSString stringWithFormat:@"SELECT *,count(distinct id) from contacts where operate='U' and name like '%%%@%%' group by id ",searchkey];
    NSMutableArray *allList  = [[NSMutableArray alloc] initWithArray:[ContactDao getDistinctContactByWhere:swheresql]];

    //过滤用户
    NSPredicate *predicateUsers = [NSPredicate predicateWithFormat:@"mTYPE != %@",@"O"];
    NSArray *usersList = [allList filteredArrayUsingPredicate:predicateUsers];
    NSMutableDictionary *userData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     @"用户", @"name", usersList, @"list", nil];
    if(usersList.count>0)
        [orgArray addObject:userData];
    //过滤机构
    NSPredicate *predicateOrg = [NSPredicate predicateWithFormat:@"mTYPE==%@",@"O"];
    NSArray *orgsList = [allList filteredArrayUsingPredicate:predicateOrg];
    NSMutableDictionary *orgsData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     @"群组", @"name", orgsList, @"list", nil];
    if(orgsList.count>0)
        [orgArray addObject:orgsData];
    
    return orgArray;
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(tableView.tag==LOCAL_GROUP)
    {
        if (searchArr.count>0) {
            return searchArr.count;
        }
        else
        {
            if (bEditing) {
                return 1;
            }
            else
                return 0;
        }
    }
    else
        return 1;
    
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(searchArr.count>0)
        return 30;
    else
        return  0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
        return  0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == LOCAL_GROUP) {
        if(searchArr.count>0)
        {
            NSMutableArray *arraysection = [[searchArr objectAtIndex:section] objectForKey:@"list"];
            return arraysection.count;
        }
        else
        {
            if (bEditing) {
                return 2;
            }
            else
                return 0;
        }

    }
    else if(tableView.tag == STRANGER_GROUP)
    {
        return stragergrpArr.count;
    }
    else if(tableView.tag == STRANGER_USER)
    {
        return strageruserArr.count;
    }
    return 0;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == LOCAL_GROUP)
    {
        if(searchArr.count>0)
        {
            Contact *contact =[[[searchArr objectAtIndex:indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
            if([contact.mTYPE isEqualToString:@"O"])//机构
            {
                MessageViewController * message = [[MessageViewController alloc]init];
                NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2G,@"messtype":@"1",@"record_DB_ID":contact.mPK_ID,@"recordID":contact.mID};
                message.sessInfo = dicc;
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
            }
            else //个人
            {
                /////20150929 自己的话，直接跳转到个人主页
                if([contact.mID isEqualToString:DE.userId]) //自己的话，弹出个人中心主界面
                {
                    NSLog(@"点击的是自己");
                    [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
                    TabbarViewController * tab = (TabbarViewController *) kAppDelegate.iCSDrawerController.centerViewController;
                    [tab.tabbar.tabbar selectItemAtIndex:4];
                }else
                {
                    MessageViewController * message = [[MessageViewController alloc]init];
                    NSDictionary *dicc = @{@"sessionType":MESSAGE_TYPE_P2P,@"messtype":@"2",@"record_DB_ID":contact.mPK_ID,
                                           @"recordID":contact.mID};
                    message.sessInfo = dicc;
                    [kAppDelegate.iCSDrawerController.navigationController pushViewController:message animated:NO];
                }
            }
        }
        else
        {
            if (bEditing) {
                if(indexPath.row==0) //从服务器上找人
                {
                    NSLog(@"从服务器上找人");
                     [_searchbar resignFirstResponder]; //键盘隐藏
                    [self FindStrangerUser];
                }
                else{
                    NSLog(@"从服务器上找群");
                    //先清空
                    [_searchbar resignFirstResponder]; //键盘隐藏
                   [self FindStrangerGrp];
                }
                
            }
        }
    }
    else if(tableView.tag == STRANGER_GROUP)
    {
         NSLog(@"点击陌生群");
        GroupInfoViewController *group = [[GroupInfoViewController alloc]init];
        group.groupid = [[stragergrpArr objectAtIndex:indexPath.row] objectForKey:@"groupId" ];
        group.grouptype= TYPE_GROUP_ORGANIZATION;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
    }
    else if(tableView.tag == STRANGER_USER)
    {
        NSLog(@"点击陌生人");
        FriendDetailViewController * frienddetail = [[FriendDetailViewController alloc] init];
        frienddetail.friendInfoDic =[strageruserArr objectAtIndex:indexPath.row];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:frienddetail animated:NO];
    }
}

-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        
        castView.contentView.backgroundColor = [UIColor colorWithWhite:0.875 alpha:1.000];
    }
}


-(void) SearchGrpTableView:(UITableView *)tab arrayData:(NSMutableArray *)arrayData key:(NSString*) key pageNo:(NSInteger*) pageNo  FooterView:(SDRefreshFooterView*)footerView
{
   //为了测试拉动分页效果，用了下面测试语句，
    //NSDictionary *map = @{@"groupType":@"1,2",@"groupName":@"",@"pageNo": [NSString stringWithFormat:@"%ld",(long)*pageNo],@"pageSize":[NSString stringWithFormat:@"%d",pageSize]};
    
    
    NSDictionary *map = @{@"groupType":@"1,2",@"groupName":sSearchKey,@"pageNo": [NSString stringWithFormat:@"%ld",(long)*pageNo],@"pageSize":[NSString stringWithFormat:@"%d",pageSize]};
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"searchGrp" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            NSArray *array =  [data objectForKey:@"grps"];
            if([array count] >0)
            {
                (*pageNo)++;
                [arrayData addObjectsFromArray:array];
                NSLog(@"XXXXXXX arrayData %ld",arrayData.count);
                //调用接口查找，如果找到了
                if(stragergrpArr.count>0)
                {
                    _tablistview.hidden = YES;
                    _tablestrageuser.hidden = YES;
                    _tablestragegrp.hidden = NO;
                    [_tablestragegrp reloadData];
                    [footerView endRefreshing];
                }
                else {
                    sSearchKey = @"";
                    bEditing = FALSE;
                    _tablistview.hidden = NO;
                    _tablestrageuser.hidden = YES;
                    _tablestragegrp.hidden = YES;
                    [_tablistview reloadData];
                }
            }
            else
            {
                if((*pageNo)==1)
                {
                    [self showAlerHUD:@"未找到相关数据"];
                    sSearchKey = @"";
                    bEditing = FALSE;
                    _tablistview.hidden = NO;
                    _tablestrageuser.hidden = YES;
                    _tablestragegrp.hidden = YES;
                    [_tablistview reloadData];
                }
            }
        }
        else{
            [self showAlerHUD:@"获取群列表失败"];
        }
       // [footerView endRefreshing];
    }];
}


//查找陌生群
-(void)FindStrangerGrp
{
    [stragergrpArr removeAllObjects];
    //首次查找重置
    organizationPageNo = 1;
    [self SearchGrpTableView:_tablestragegrp arrayData:stragergrpArr key:@"" pageNo:&organizationPageNo FooterView:nil];
    
}


- (void)setupHeader
{
    refreshOrganizationFooterView = [SDRefreshFooterView refreshView];
    
    [refreshOrganizationFooterView addToScrollView:_tablestragegrp];
    
    [refreshOrganizationFooterView addTarget:self refreshAction:@selector(OrganizationfooterRefresh)];
}

- (void)dealloc
{
    [refreshOrganizationFooterView removeFromSuperview];
}



- (void)OrganizationfooterRefresh
{
    NSLog(@"XXXXXXXXXXXXXXXXXX");
    
   [self SearchGrpTableView:_tablestragegrp arrayData:stragergrpArr key:@"" pageNo:&organizationPageNo FooterView:refreshOrganizationFooterView];
}



//查找陌生人
-(void)FindStrangerUser
{
    if(sSearchKey.length>0)
    {
        NSDictionary *map = @{@"keyword":sSearchKey};
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"findUser" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
           [MBProgressHUD hideHUDForView:self.view animated:YES];
            if(success)
            {
                strageruserArr = [data objectForKey:@"users"];
                //调用接口查找，如果找到了
                if(strageruserArr.count>0)
                {
                    _tablistview.hidden = YES;
                    _tablestrageuser.hidden = NO;
                    _tablestragegrp.hidden = YES;
                    [_tablestrageuser reloadData];
                }
                else {
                   [self showAlerHUD:@"未找到此联系人"];
                    sSearchKey = @"";
                    bEditing = FALSE;
                    _tablistview.hidden = NO;
                    _tablestrageuser.hidden = YES;
                    _tablestragegrp.hidden = YES;
                    [_tablistview reloadData];
                }
            }
            else{
                [self showAlerHUD:@"查找人失败"];
            }
        }];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == LOCAL_GROUP || tableView.tag == STRANGER_GROUP)
    {
        static NSString * CellIdentifier = @"GroupTableViewCell";
        GroupTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
            cell.imgHead.layer.masksToBounds = YES;
            cell.imgHead.layer.cornerRadius = 16;
        }
        
        if(tableView.tag == LOCAL_GROUP)
        {
            if(searchArr.count>0)
            {
                Contact *contact =[[[searchArr objectAtIndex:indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
                //头像
                NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
                [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
                //名称
                cell.labTitle.text = contact.mNAME;
                cell.labTitle.font = [UIFont systemFontOfSize:15];
                
                //机构
                if(![contact.mTYPE isEqualToString:@"O"])
                {
                    UILabel * titlaLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 15, 100, 20)];
                    titlaLabel.text = contact.mDEPT;
                    titlaLabel.font = [UIFont systemFontOfSize:12];
                    titlaLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
                    titlaLabel.textAlignment = NSTextAlignmentRight;
                    [cell addSubview:titlaLabel];
                }
            }else //找不到人或者群
            {
                if (bEditing) {
                    if(indexPath.row==0)
                    {
                        cell.imgHead.image = [UIImage imageNamed:@"find_user.png"];
                        cell.labTitle.text =[[NSString alloc]initWithFormat:@"  找人：%@",sSearchKey];
                        
                    }
                    else if(indexPath.row==1)
                    {
                        cell.imgHead.image = [UIImage imageNamed:@"find_group.png"];
                        cell.labTitle.text =[[NSString alloc]initWithFormat:@"  找群：%@",sSearchKey];
                    }
                }
                
            }
        }
        else //STRANGER_GROUP 陌生群
        {
            cell.labTitle.text = [[stragergrpArr objectAtIndex:indexPath.row] objectForKey:@"groupName" ];
            NSString *sHeadImg = [[stragergrpArr objectAtIndex:indexPath.row] objectForKey:@"headImg" ];
            NSURL *url= [NSURL URLWithString: [sHeadImg hasPrefix:@"http"]?sHeadImg:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,sHeadImg]];
            
            [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"group"]];
        }
         return  cell;
    }
    else /*if(tableView.tag == STRANGER_USER)*/ //陌生人
    {
        static NSString * CellIdentifier = @"SearchinforTableViewCell";
        SearchinforTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        }
        NSDictionary * dic =[strageruserArr objectAtIndex:indexPath.row];
        NSString * str = [NSString stringWithFormat:@"%@(%@)",[dic objectForKey:@"userName" ],[[dic objectForKey:@"type"] isEqualToString:@"T"]?@"教职工":@"学生"];
        NSURL *url= [NSURL URLWithString: [[dic objectForKey:@"headImg"] hasPrefix:@"http"]?[dic objectForKey:@"headImg"]:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,[dic objectForKey:@"headImg"]]];
        cell.headImage.layer.masksToBounds = YES;
        cell.headImage.layer.cornerRadius = 8.0;
        [cell.headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        cell.nameLabel.text = str;
        cell.detailLabel.text = [[NSString alloc]initWithFormat:@"%@/%@", [dic objectForKey:@"dept"],[dic objectForKey:@"profName"]];
        return  cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == STRANGER_USER)
      return 60;
    else
        return 50;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(searchArr.count==0)
        return @"";
    else
       return [[searchArr objectAtIndex:section] objectForKey:@"name"];
    
}


//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImage:[UIImage imageNamed:@""]  text:text];
    hudex.center = CGPointMake(self.view.center.x, self.view.center.y+210);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.0 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end
